import 'package:amway_superapp_creator_plugin/analysis/zhuge_goods_recommendation.dart';
import 'package:amway_superapp_creator_plugin/models/choose_shop_bean.dart';
import 'package:amway_superapp_creator_plugin/models/circle_detail_model.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/models/search_info_bean.dart';
import 'package:amway_superapp_creator_plugin/models/shop_list_model.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../../api.dart';

class RelatedShopModel extends BaseModel {
  RelatedShopModel({@required Api api}) : super(api: api);

  bool _isLoading = false;
  bool _greyButton = false;

  int _pageNo = 1;
  String _skuCode = '';

  String get skuCode => _skuCode;

  set skuCode(String value) {
    _skuCode = value;
  }

  int get pageNo => _pageNo;

  set pageNo(int value) {
    _pageNo = value;
  }

  EasyRefreshController _refreshController = EasyRefreshController();

  EasyRefreshController get refreshController => _refreshController;

  void deleteItem(int index) {
    shopList.removeAt(index);
    notifyListeners();
  }

  set refreshController(EasyRefreshController value) {
    _refreshController = value;
  }

  void setShop(List<HaowuProduct> list) {
    shopList=list;
    notifyListeners();
  }

  List<ChooseShopBean> _category = [];

  List<ChooseShopBean> get category => _category;
  List<HaowuProduct> shopList = [];
  int position = 0;

  void getCategoryList() {
    HttpManager().get(
        url: "apis/v1/creator/product/categoryList",
        tag: null,
        successCallback: (data) {
          if (data != null) {
            _category.clear();
            for (var v in data) {
              _category.add(ChooseShopBean.fromJson(v));
            }
            _category[0].isChecked = true;
            _category.forEach((element) {
              element.categoryName =
                  element.categoryName.replaceAll(RegExp('sup'), '');
              element.categoryName =
                  element.categoryName.replaceAll(RegExp('>'), '');
              element.categoryName =
                  element.categoryName.replaceAll(RegExp('<'), '');
              element.categoryName =
                  element.categoryName.replaceAll(RegExp('/'), '');
              element.childNavigationNode.insert(
                  0,
                  ChildNavigationNodeBean(
                      childNodeName: "全部系列", code: element.categoryCode));
            });
            notifyListeners();
          }
        },
        errorCallback: (data) {});
  }

  ShopListBean shopDataBean = ShopListBean();

  void clearShopList() {
    if (shopList != null && shopList.isNotEmpty) {
      shopList.clear();
    }
  }

  void getShopList2(SearchInfoBean bean, int loadType) {
    if (!isLoading) {
      isLoading = true;
    } else {
      return;
    }
    bean.pageNo = pageNo;
    if (skuCode != null && skuCode.isNotEmpty) {
      bean.lastSkuCode = skuCode;
    }
    api.getShopList(bean, (success) {
      if (success != null) {
        try {
          ShopListBean shopListBean = ShopListBean.fromJson(success);
          bool noMore=pageNo==shopListBean.nextPageNumber;
          pageNo = shopListBean.nextPageNumber;
          int initLength = 0;
          if (shopListBean.content != null && shopListBean.content.isNotEmpty) {
            initLength = shopListBean.content.length;
            shopListBean.content.forEach((element) {
              if (element.approvalStatus == "APPROVED" &&
                  element.orderable == true &&
                  element.priceData.saleStatus == "ACTIVE") {
                shopList.add(element);
              }
            });
            skuCode = shopList.last.skuCode;
          }

          switch (loadType) {
            case 0:
              markCached();
              if (initLength < 20||noMore) {
                _refreshController.finishLoad();
              }
              break;
          //刷新
            case 1:
              markCached();
              if (initLength < 20||noMore) {
                _refreshController.finishRefresh();
              } else {
                _refreshController.finishRefresh();
              }
              break;
            case 2:
            //加载更多
            markCached();
              if (initLength < 20||noMore) {
                _refreshController.finishLoad(noMore: true);
              } else {
                _refreshController.finishLoad();
              }
              break;
          }
          notifyListeners();
        } on Exception catch (e) {
          // 任意一个异常
          ToastUtils.showShortToast(e.toString());
        } catch (e) {
          // 非具体类型
          ToastUtils.showShortToast(e.toString());
        }
        isLoading = false;
      }
    }, (failure) {
      _refreshController.finishLoad();
      _refreshController.finishRefresh();
      ToastUtils.showLongToast(failure.toString());
      isLoading = false;
      notifyListeners();
    });
  }

  List<HaowuProduct> _checkedShop = [];
/*
* 选中的商品
* */
  List<HaowuProduct> getCheckedShop() {
    _checkedShop = [];
    if (shopList == null || shopList.isEmpty) {
      return _checkedShop;
    }
    shopList.forEach((element) {
      if (element.isChecked) {
        _checkedShop.add(element);
      }
    });
    return _checkedShop;
  }

  /*
  * 商品选中
  * */
  void setChecked(int index) {
    int length=0;
    if(cachedList!=null&&cachedList.isNotEmpty){
      cachedList.forEach((element) {
        if(!element.isHidden){
          length++;
        }
      });
    }
    if (!shopList[index].isChecked) {
      if (getCheckedShop().length+length + 1 > 50) {
        ToastUtils.showShortToast('最多只能添加50个商品哦');
        return;
      } else {}
    } else {
      // if(cachedList!=null){
      //   for(int i=0;i<cachedList.length;i++){
      //     if(shopList[index].skuCode==cachedList[i].skuCode){
      //       cachedList[i].isHidden=true;
      //       break;
      //     }
      //   }
      // }
    }

    shopList[index].isChecked = !shopList[index].isChecked;

    if(shopList[index].isChecked){
      ZhugeGoodsRecommendationAnalysis.goodsReCommendaionAddGoods("商品列表页面");
    }

    if (getCheckedShop().length+length == 50) {
      _greyButton = true;
    } else {
      _greyButton = false;
    }
    notifyListeners();
  }

/*
* 是否收起
* */
  void isStop(ChildNavigationNodeBean bean) {
    bean.isVisible = !bean.isVisible;
    notifyListeners();
  }

/*
* 分类是否选中
* */
  void isChecked(int index) {
    this.position = index;
    category.forEach((element) {
      element.isChecked = false;
    });
    category[index].isChecked = !category[index].isChecked;
    notifyListeners();
  }

  bool get isLoading => _isLoading;

  set isLoading(bool value) {
    _isLoading = value;
  }

/*
* 回现数据
* */
  void showShopData(List<Products> products) {
    shopList.clear();
    if (products != null && products.length > 0) {
      products.forEach((element) {
        shopList.add(HaowuProduct(
            priceData: element.priceData,
            skuName: element.skuName,
            itemSku: element.itemSku,
            productName: element.productName,
            skuCode: element.skuCode,
            picture: element.picture));
      });
    }
    notifyListeners();
  }

  List<HaowuProduct> _cachedList;

  List<HaowuProduct> get cachedList => _cachedList;

  set cachedList(List<HaowuProduct> value) {
    _cachedList = value;
  }

  void markCached() {
    if(cachedList!=null&&cachedList.isNotEmpty){
      int length=cachedList.length;
      for (int i = 0; i < cachedList.length; i++) {
        shopList.forEach((element) {
          if (cachedList[i].skuCode == element.skuCode) {
            element.isChecked = true;
            cachedList[i].isHidden=true;
            length--;
          }
        });
      }
      cachedList.removeWhere((element) => element.isHidden);
      if (getCheckedShop().length+length >= 50) {
        _greyButton = true;
      } else {
        _greyButton = false;
      }
      notifyListeners();
    }
  }

  bool get greyButton => _greyButton;

  set greyButton(bool value) {
    _greyButton = value;
  }

  List<HaowuProduct> getReturnShopList(){
    if(cachedList==null||cachedList.isEmpty){
      cachedList=[];
    }
    List<HaowuProduct> checkedList=getCheckedShop();
    checkedList.forEach((checked) {
      // bool repeated=false;
      // cachedList.forEach((cached) {
      //   if(checked.skuCode==cached.skuCode){
      //     repeated=true;
      //   }
      // });
      // if(!repeated){
      //
      // }
      cachedList.insert(0, checked);
    });

    return cachedList;
  }
}
